﻿using MiniErp.Model.Entities;
using MiniErp.Model.Templates;
using MiniErp.Repository.IRepository;
using MiniErp.DBService.Service.IService;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;

namespace MiniErp.DBService.Service.Service
{
    public class LoginService : ILoginService
    {
        private readonly IUsetInfoRepository _uir;
        public LoginService(IUsetInfoRepository uir)
        {
            _uir = uir;
        }



        public async Task<MessageTemplate<UserInfoEntity>> Login(int id, string password)
        {
           var message = new MessageTemplate<UserInfoEntity>();
            if (id == 0 || string.IsNullOrWhiteSpace(password))
            {
                message.Status = 403;
                message.Message = $"用户名或者密码不能为空";
            }
            try
            {
                var num = await _uir.GetUserisExistenceAsync(id);
                if (num == 0)
                {
                    message.Status = 403;
                    message.Message = $"数据库中不存在工号为{id}的用户";
                }
                else if (num == 1)
                {
                    var result = await _uir.GetUserInfoAsync(id, password);
                    if (result == null)
                    {
                        message.Status = 403;
                        message.Message = $"用户名或者密码错误";
                    }
                    else
                    {
                        message.Status = 200;
                        message.Message = $"登录成功";
                        message.data.Add(result);

                    }
                }
                else
                {
                    message.Status = 500;
                    message.Message = $"该用户账号信息异常";
                }
            }
            catch (Exception ex)
            {
                message.Status = 500;
                message.Message = $"服务器异常,异常信息为:{ex.Message}";
                message.data = null;
            }
            return message;
        }

        public async Task<MessageTemplate<int>> Register(UserInfoEntity userinfo)
        {
            MessageTemplate<int> message = new MessageTemplate<int>();
            var num = await _uir.AddUserInfoAsync(userinfo);
            if (num == 0)
            {
                message.Status = 401;
                message.Message = "注册失败";
            }
            else if (num == 1)
            {
                message.Status = 200;
                message.Message = "注册成功";
            }
            else
            {
                message.Status = 500;
                message.Message = "注册出现异常";
            }
            message.data.Add(num);
            return message;
        }
    }
}
